import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
})
// 请求拦截器
service.interceptors.request.use((config) => {
  if (store.getters.token) {
    config.headers.Authorization = store.getters.token
  }
  return config
}, (error) => Promise.reject(error))
// 响应拦截器
service.interceptors.response.use((response) => {
  const { code, msg, data } = response.data
  if (code === 10000) {
    return data
  }
  Message.error(msg)
  return Promise.reject(new Error(msg))
}, error => {
  if (error.response.status === 401) {
    store.dispatch('user/logout')
    router.push('/login')
    Message.error('登录失效，请重新登录')
  } else {
    Message.error(error.message)
  }
  return Promise.reject(error)
})

export default service
